package com.heima.admin.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *      认证过滤器
 */
@Component
@Slf4j
@Order(0)
public class AppFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();
    static {
        urlList.add("/login_auth/");
        urlList.add("/v2/api-docs");
//        urlList.add("api/v1/read_behavior");

    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            //1.  判断当前是否是登录请求（从请求中获取请求路径是登录请求则放行）
            ServerHttpRequest request = exchange.getRequest();
            String reqUri = request.getURI().getPath();
            for (String url : urlList) {
                if (reqUri.contains(url)) {
                    return chain.filter(exchange);
                }
            }
            //2. 获取请求头中的JWT token信息
            String token = request.getHeaders().getFirst("token");
            if (StringUtils.isBlank(token)) {
                return writeMessage(exchange,"未登录，请登录");
            }
            //3. 判断token是否正确
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //-1：有效，0：有效，1：过期，2：过期
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (verifyToken > 0) {
                return writeMessage(exchange,"登录过期，请重新登录");
            }
            //3. 解析token
            Integer id = claims.get("id", Integer.class);
            log.info("token校验成功，用户id：{}，url:",id,request.getURI().getPath());
            //4.  将token传到微服务中
            request.mutate().headers(
                    httpHeaders -> {
                        httpHeaders.add("userId", String.valueOf(id));
                    }
            );
            exchange.mutate().request(request);
            return chain.filter(exchange);
        } catch (Exception e) {
            log.error("token校验失败{}",e);
            return writeMessage(exchange,"认证过程失败，请重试");
        }
    }

    /**
     *       返回类型提示信息
     * @param exchange
     * @param message
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message){
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));

    }
}


